<template>
  <div id="app">
    <my-checkbox v-model="flag" />
    <my-checkbox v-model="flag">全选</my-checkbox>
    <number-input v-model="num"></number-input>
    <!-- 这里要加:width,这样它才会解析 -->
    <my-button :width="200" :height="100">点击</my-button>
    <!-- 这里就是我哪一项改变了，我就删除哪个下标，并且删除一个 -->
    <!-- // var arr=[{a:1},{b:2},{c:3}]
    // arr.splice(1,1,{b:3})  //[{a:1},{b:3},{c:3}] -->
    <cart-item v-for="(cart,index) in cartList" :key="cart.id" v-bind="cart" 
    @change1="cartList.splice(index,1,$event)"
    @delete ="cartList.splice(index,1)"></cart-item>
    <!-- 根据索引值删除对应的旧数据，把$event当做新数据插进来-->
    <cart-footer v-bind="cartTotal" @all-check="onAllCheck"></cart-footer>
  </div>
</template>

<script>
// @相当于是一个路径的,src文件夹的别名，写.也一样
import MyCheckbox from "@/components/MyCheckbox.vue";
import NumberInput from "./components/NumberInput.vue";
import MyButton from "./components/MyButton.vue";
import CartItem from "./components/CartItem.vue";
import CartFooter from './components/CartFooter.vue';

const cartList = [
  {
    id: 1,
    title: "【新人专享】按摩颈椎 泰国93%天然乳胶枕",
    img: "/img/01.webp",
    price: 179.0,
    num: 1,
    checked: true,
  },
  {
    id: 2,
    title: "T30无限吸尘器【配件】",
    img: "/img/02.webp",
    price: 159.0,
    num: 2,
    checked: true,
  },
  {
    id: 3,
    title: "免费抽取，放心存放，一次性食品保鲜袋",
    img: "/img/03.webp",
    price: 12.9,
    num: 2,
    checked: true,
  },
  {
    id: 4,
    title: "多功能人体工学转椅",
    img: "/img/04.webp",
    price: 1228.0,
    num: 2,
    checked: true,
  },
];

export default {
  name: "App",
  components: {
    MyCheckbox,
    NumberInput,
    MyButton,
    CartItem,
    CartFooter,
  },
  data() {
    return {
      flag: true,
      num: 10,
      cartList,
    };
  },
  computed:{
    cartTotal(){
      // reduce的参数，第一个回调函数(回调函数上一次的返回值，数组的每一项成员，索引，数组本身)，
      // 第二个初始值
      return this.cartList.reduce((prev,cart) =>{
        return {
           totalNum: prev.totalNum + (cart.checked?cart.num:0),
           totalPrice: prev.totalPrice + (cart.checked?cart.num * cart.price:0),
           allChecked: prev.allChecked && cart.checked
        }
      },{
        totalNum: 0,
        totalPrice: 0,
        allChecked: true,

      })
    }
  },
  methods:{
    onAllCheck($event){
      this.cartList.forEach(cart =>cart.checked = $event)

    }
  }
};


</script>

<style lang="scss">
</style>
